/*
 * 本类作用：mina框架:解码器，用于接收数据时拆包
 * 
 * 作者：袁小杰
 * 博客：http://blog.csdn.net/undoner
 * GIT：https://git.oschina.net/undoner
 * QQ：15137281
 * 
 */
package com.smforj.ssm.mina.codec;
 
import java.nio.charset.Charset;

import org.apache.log4j.Logger;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.CumulativeProtocolDecoder;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;

/***
 * 解码器，用于接收数据时拆包
 * 
 * @author Haijun Gao 
 * @date 2016-7-28 上午8:49:37
 * @desp http://www.cnblogs.com/saga5998/
 * @email 573107773@qq.com
 */
public class TestMsgDecoder extends CumulativeProtocolDecoder  {

	static Logger log = Logger.getRootLogger(); 
	private final Charset charset;
	public TestMsgDecoder() {
		this(Charset.defaultCharset());
	}

	public TestMsgDecoder(Charset charset) {
		this.charset = charset;
	}
	
	/***
	 * 数据解析
	 */
	@Override
	protected boolean doDecode(IoSession session, IoBuffer in,
			ProtocolDecoderOutput out) throws Exception {    
    	//将所以数据读取到byte数组中
    	byte[] dst = new byte[in.limit()];
    	in.mark();//标记当前位置，以便reset
    	in.get(dst);   
        String pack = new String(dst,charset);
        //String pack = MsgUtils.ioBufferToString(IoBuffer.wrap(bytes)); 
        out.write(pack); 
        if(in.remaining() > 0){//如果读取内容后还粘了包，就让父类再重读  一次，进行下一次解析  
           return true;  
        }  
        return false;//处理成功，让父类进行接收下个包  
	}  
}
